import './css/index.css';
import img1 from './img/1.jpeg';
import img2 from './img/2.jpeg';
import img3 from './img/3.jpeg';

const list = [img1, img2, img3];
// 面向对象 / 面向过程
// 定义一个类（构造函数）

function Light($box) {
  // 装红绿灯的容器
  this.box = document.querySelector($box);
  // 初始值
  this.index = 1;
  this.flag = true;
  this.timer;
}

// 初始化图片方法
Light.prototype.init = function () {
  console.log('初始化图片');
  // 创建图片标签
  this.img = new Image();
  // 禁止拖拽
  this.img.draggable = false;
  this.img.src = `${list[this.index - 1]}`;
  // 添加图片
  this.box.appendChild(this.img);
};

Light.prototype.bindClick = function () {
  this.img.addEventListener('click', () => {
    // this.index++;
    this.index = (this.index % 3) + 1;
    // 判断图片是否123
    // this.index > 3 && (this.index = 1);
    // 修改图片地址
    this.img.src = `${list[this.index - 1]}`;
  });
};

// 自动轮播
Light.prototype.autoPlay = function () {
  this.timer = setInterval(() => {
    if (this.flag && this.index < 3) {
      this.index++;
    } else {
      this.flag = false;
      this.index--;
      if (this.index == 1) {
        this.flag = true;
      }
    }
    // 修改图片地址
    this.img.src = `${list[this.index - 1]}`;
  }, 500);
};

// 鼠标移入事件
Light.prototype.moveFn = function () {
  this.img.addEventListener('mouseenter', () => {
    clearInterval(this.timer);
  });
  this.img.addEventListener('mouseleave', () => {
    this.autoPlay();
  });
};

//反向点击
Light.prototype.bindReClick = function () {
  this.img.addEventListener('click', () => {
    this.index--;
    this.index < 1 && (this.index = 3);
    // 修改图片地址
    this.img.src = `${list[this.index - 1]}`;
  });
};
// 顺序上到下
let l1 = new Light('.box1');
l1.init();
l1.bindClick();

// 自动播放上到下（可控制）
let l2 = new Light('.box2');
l2.init();
l2.autoPlay();
l2.moveFn();

//顺序下到上
let l3 = new Light('.box3');
l3.init();
l3.bindReClick();
